{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Keras MNIST CNN"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    }
   ],
   "source": [
    "import keras\n",
    "from keras.datasets import mnist\n",
    "from keras.models import Sequential\n",
    "from keras.layers import Dense, Dropout, Flatten\n",
    "from keras.layers import Conv2D, MaxPooling2D\n",
    "from keras import backend as K"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. 设定参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_size = 128\n",
    "num_classes = 10\n",
    "epochs = 12\n",
    "img_rows, img_cols = 28, 28"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. 处理数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x_train shape: (60000, 28, 28, 1)\n",
      "60000 train samples\n",
      "10000 test samples\n"
     ]
    }
   ],
   "source": [
    "(x_train, y_train), (x_test, y_test) = mnist.load_data(already_path=\"data/mnist.npz\")\n",
    "\n",
    "if K.image_data_format() == 'channels_first':\n",
    "    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)\n",
    "    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)\n",
    "    input_shape = (1, img_rows, img_cols)\n",
    "else:\n",
    "    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\n",
    "    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\n",
    "    input_shape = (img_rows, img_cols, 1)\n",
    "\n",
    "x_train = x_train.astype('float32')\n",
    "x_test = x_test.astype('float32')\n",
    "x_train /= 255\n",
    "x_test /= 255\n",
    "print('x_train shape:', x_train.shape)\n",
    "print(x_train.shape[0], 'train samples')\n",
    "print(x_test.shape[0], 'test samples')\n",
    "\n",
    "# convert class vectors to binary class matrices\n",
    "y_train = keras.utils.to_categorical(y_train, num_classes)\n",
    "y_test = keras.utils.to_categorical(y_test, num_classes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. 建立模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Logging before flag parsing goes to stderr.\n",
      "W0211 17:26:13.425381  2372 deprecation_wrapper.py:119] From D:\\dev_tools\\anaconda\\lib\\site-packages\\keras\\backend\\tensorflow_backend.py:4070: The name tf.nn.max_pool is deprecated. Please use tf.nn.max_pool2d instead.\n",
      "\n",
      "W0211 17:26:14.678245  2372 deprecation_wrapper.py:119] From D:\\dev_tools\\anaconda\\lib\\site-packages\\keras\\backend\\tensorflow_backend.py:422: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train on 60000 samples, validate on 10000 samples\n",
      "Epoch 1/12\n",
      "60000/60000 [==============================] - 85s 1ms/step - loss: 0.2665 - accuracy: 0.9183 - val_loss: 0.0560 - val_accuracy: 0.9820\n",
      "Epoch 2/12\n",
      "60000/60000 [==============================] - 83s 1ms/step - loss: 0.0891 - accuracy: 0.9743 - val_loss: 0.0411 - val_accuracy: 0.9864\n",
      "Epoch 3/12\n",
      "60000/60000 [==============================] - 83s 1ms/step - loss: 0.0657 - accuracy: 0.9802 - val_loss: 0.0354 - val_accuracy: 0.9873\n",
      "Epoch 4/12\n",
      "60000/60000 [==============================] - 83s 1ms/step - loss: 0.0553 - accuracy: 0.9834 - val_loss: 0.0281 - val_accuracy: 0.9894\n",
      "Epoch 5/12\n",
      "60000/60000 [==============================] - 83s 1ms/step - loss: 0.0471 - accuracy: 0.9855 - val_loss: 0.0285 - val_accuracy: 0.9900\n",
      "Epoch 6/12\n",
      "60000/60000 [==============================] - 83s 1ms/step - loss: 0.0404 - accuracy: 0.9881 - val_loss: 0.0264 - val_accuracy: 0.9902\n",
      "Epoch 7/12\n",
      "60000/60000 [==============================] - 83s 1ms/step - loss: 0.0365 - accuracy: 0.9883 - val_loss: 0.0296 - val_accuracy: 0.9906\n",
      "Epoch 8/12\n",
      "60000/60000 [==============================] - 83s 1ms/step - loss: 0.0342 - accuracy: 0.9894 - val_loss: 0.0286 - val_accuracy: 0.9913\n",
      "Epoch 9/12\n",
      "60000/60000 [==============================] - 83s 1ms/step - loss: 0.0313 - accuracy: 0.9907 - val_loss: 0.0263 - val_accuracy: 0.9912\n",
      "Epoch 10/12\n",
      "60000/60000 [==============================] - 83s 1ms/step - loss: 0.0292 - accuracy: 0.9909 - val_loss: 0.0294 - val_accuracy: 0.9905\n",
      "Epoch 11/12\n",
      "60000/60000 [==============================] - 83s 1ms/step - loss: 0.0269 - accuracy: 0.9918 - val_loss: 0.0254 - val_accuracy: 0.9923\n",
      "Epoch 12/12\n",
      "60000/60000 [==============================] - 84s 1ms/step - loss: 0.0258 - accuracy: 0.9922 - val_loss: 0.0242 - val_accuracy: 0.9927\n",
      "Test loss: 0.02416915106639208\n",
      "Test accuracy: 0.9926999807357788\n"
     ]
    }
   ],
   "source": [
    "model = Sequential()\n",
    "model.add(Conv2D(32, kernel_size=(3, 3),\n",
    "                 activation='relu',\n",
    "                 input_shape=input_shape))\n",
    "model.add(Conv2D(64, (3, 3), activation='relu'))\n",
    "model.add(MaxPooling2D(pool_size=(2, 2)))\n",
    "model.add(Dropout(0.25))\n",
    "model.add(Flatten())\n",
    "model.add(Dense(128, activation='relu'))\n",
    "model.add(Dropout(0.5))\n",
    "model.add(Dense(num_classes, activation='softmax'))\n",
    "\n",
    "model.compile(loss=keras.losses.categorical_crossentropy,\n",
    "              optimizer=keras.optimizers.Adadelta(),\n",
    "              metrics=['accuracy'])\n",
    "\n",
    "model.fit(x_train, y_train,\n",
    "          batch_size=batch_size,\n",
    "          epochs=epochs,\n",
    "          verbose=1,\n",
    "          validation_data=(x_test, y_test))\n",
    "score = model.evaluate(x_test, y_test, verbose=0)\n",
    "print('Test loss:', score[0])\n",
    "print('Test accuracy:', score[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
